-- NewguildManagePanel

local NewguildIconRender = import(".renders.NewguildIconRender")
local NewguildApplyRender = import(".renders.NewguildApplyRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local ClassRef = app.mvc.createPanelClass(...)

local NoticeMaxWordNum = tonumber( GD:getSystemPar("guildNoticeMaxWordNum", 20) ) -- 公告最大字符数
local DeclareMaxWordNum = tonumber( GD:getSystemPar("guildDeclareMaxWordNum", 60) ) -- 宣言最大字符数

local maxPlayerLv = tonumber(GD:getSystemPar( "maxlvforpro", 99 ))
local maxCombatPower = tonumber(GD:getSystemPar( "maxCombatPower", 9990000 ))

local minPlayerLv = tonumber(GD:getSystemPar( "guildExamineMinLV", 1 ))
local minCombatPower = tonumber(GD:getSystemPar( "guildExamineMinPower", 1000 ))

local table_insert = table.insert
function ClassRef.create(node)
	local sprite = ClassRef.extend(node)
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	self._curIdx = 0 -- 当前所处的panelIdx

	self._ui.Panel_left:findChild( "Button_donate" ):addClickEventListener(function()
		executeFunc(self._onOperate, "openDonate")
	end)

	--跳转到公会排行界面的按钮
	self._ui.Panel_left:findChild("Button_rank"):addClickEventListener(
		function()
			UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK,mode = "open", rankingId = Enums.GuildRankType.GuildLv})
		end
	)

	self._ui.Panel_recruit:findChild( "Button_enter" ):addClickEventListener(function()
		local function checkCB( strTemp )
			if self and self._ui then
				--判断宣言长度
				local ulen = string.counting(strTemp)
				if ulen > DeclareMaxWordNum then
					display.pushToast(string.format(L("lua_code_text_315"), DeclareMaxWordNum))
				else
					self._declareText:setText( strTemp )
					executeFunc(self._onOperate, "change_guild_declare", strTemp )
				end
			end
		end

		local str = self._declareText:getText()
		if app:isNeedCheckInput() then
			app:checkInput(str, function(response,errorMsg,code)
				if code == 200 then
					if response and response.result then
						str = response.result
						checkCB( str )
					end
				else
					display.pushToast(L("network_error"))
				end
			end, true)
		else
			checkCB( str )
		end
	end)

	self._lvPanel = self._ui["Panel/Panel_right/Panel_set/Panel_lv"]
	self._combatPanel = self._ui["Panel/Panel_right/Panel_set/Panel_combat"]
	self._autoApplyPassBtn = self._ui["Panel/Panel_right/Panel_set/Panel_btn/selected_btn"]

	self._autoApplyPassBtn:addTouchEventListener(handler( self, self.setAutoApplyPass ) )

	self:_selectedPanel( 1 )
	self._ui.Panel_btn:findChild( "Button_1" ):addClickEventListener(function()
		self:_selectedPanel( 1 )
	end)
	self._ui.Panel_btn:findChild( "Button_2" ):addClickEventListener(function()
		self:_selectedPanel( 2 )
	end)

	self._ui.Panel_btn:findChild( "Button_3" ):addClickEventListener(function()
		self:_selectedPanel( 3 )
	end)

	--一键同意 和 一键拒绝
	self._ui.Panel_list:findChild("Button_quxiao"):addClickEventListener(function()
		local applyListData =  self._applyList:getData()

		--if #applyListData > 0 then
			executeFunc(self._onOperate, "applyRender_Op", { false, {} } )
		--end
	end)

	self._ui.Panel_list:findChild("Button_queding"):addClickEventListener(function()
		local applyListData =  self._applyList:getData()

		--if #applyListData > 0 then
			executeFunc(self._onOperate,"applyRender_Op", { true, {} } )
		--end
	end)



	self._guildName = self._ui.Panel_left:getChildByName( "name" ) -- 公会名字
	self._guildIcon = NewguildIconRender.create( self._ui.Panel_left:getChildByName( "icon" ) ) -- 公会头像

	local onlinePanel = self._ui.Panel_left:getChildByName( "Panel_p" )
	display.uiAddClick( onlinePanel, function()
		local posTemp = onlinePanel:convertToWorldSpace(cc.p(0,0))
		local width, height = onlinePanel:getContentSize2()
		posTemp.x = posTemp.x + width
		executeFunc(self._onOperate, "showTips_onLine", posTemp )
	end )
	self._onlineMemberNum = onlinePanel:getChildByName( "num" ) -- 在线人数

	local lvPanel = self._ui.Panel_left:getChildByName( "Panel_lv" )
	display.uiAddClick( lvPanel, function()
		local posTemp = lvPanel:convertToWorldSpace(cc.p(0,0))
		local width, height = lvPanel:getContentSize2()
		posTemp.x = posTemp.x + width
		executeFunc(self._onOperate, "showTips_Lv", posTemp )
	end )
	self._guildLv = lvPanel:getChildByName( "num" ) -- 等级
	local expBar = lvPanel:getChildByName( "guild_bar" ) -- 公会经验值
	expBar:setVisible( false )
	self._guildExp = cc.ProgressTimer:create( expBar )
	self._guildExp:setType( cc.PROGRESS_TIMER_TYPE_RADIAL )
	self._guildExp:setMidpoint(display.ANCHOR_POINTS[1])
	self._guildExp:setPosition( expBar:getPosition() )
	lvPanel:addChild( self._guildExp )

	local guildGoldPanel = self._ui.Panel_left:getChildByName( "Panel_m" )
	display.uiAddClick( guildGoldPanel, function()
		local posTemp = guildGoldPanel:convertToWorldSpace(cc.p(0,0))
		local width, height = guildGoldPanel:getContentSize2()
		posTemp.x = posTemp.x + width
		executeFunc(self._onOperate, "showTips_donate", posTemp )
	end )

	self._guildCoinNum = guildGoldPanel:getChildByName( "num" ) -- 公会资金

	local params = {
		renderClass = NewguildApplyRender,
		perNum = 1,
		cellEventProxy = function(eventName, params)
			executeFunc(self._onOperate, eventName, params)
		end
	}

	self._applyList = ListViewVertical.new( self._ui.ScrollView, params )

	self:_initNoticeEditBox()
	self:_initDeclareEditBox()


	local lvMinusBtn = self._lvPanel:findChild("Button_minus")
	lvMinusBtn:addTouchEventListener(handler( self, self._lvMinusBtnClickEvent ) )
	local lvPlusBtn = self._lvPanel:findChild("Button_plus")
	lvPlusBtn:addTouchEventListener(handler( self, self._lvPlusBtnClickEvent ) )
	self._needLvText = self._lvPanel:findChild("num") --入会需要的最低等级

	local panelBg = self._lvPanel:findChild("bg")
	display.uiAddClick( panelBg, function()
		local btn = self._lvPanel:findChild("Button_plus")
		local posTemp = btn:convertToWorldSpace(cc.p(0,0))
		local width, height = btn:getContentSize2()
		posTemp.x = posTemp.x + width
		executeFunc(self._onOperate, "showMiniKeyboard", {posTemp,self._needLv,
			function(lv)
				self:setAutoApplyLvLimit(lv)
				executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
			end
			} )
	end )


	local combatMinusBtn = self._combatPanel:findChild("Button_minus")
	combatMinusBtn:addTouchEventListener(handler( self, self._powerMinusBtnClickEvent ) )
	local combatPlusBtn = self._combatPanel:findChild("Button_plus")
	combatPlusBtn:addTouchEventListener(handler( self, self._powerPlusBtnClickEvent ) )
	self._needPowerText = self._combatPanel:findChild("num") --入会需要的最低战力

	panelBg = self._combatPanel:findChild("bg")
	display.uiAddClick( panelBg, function()
		local btn = self._combatPanel:findChild("Button_plus")
		local posTemp = btn:convertToWorldSpace(cc.p(0,0))
		local width, height = btn:getContentSize2()
		posTemp.x = posTemp.x + width

		executeFunc(self._onOperate, "showMiniKeyboard", {posTemp,self._needPower,
			function(power)
				self:setAutoApplyPowerLimit(power)
				executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
			end
			} )
	end )

	
	self._ui["Panel/Panel_left/Button_im"]:addClickEventListener(handler(self, self._onMsdkGroupBind))
    self:registerViewEvent({
        {name = ViewEvent.Msdk_GuildBindedChange, callback = handler(self, self.refreshMsdkGroupBinded)},
	})
	self:refreshMsdkGroupBinded()
end

-- 公告编辑框 处理
function ClassRef:_initNoticeEditBox()
	local function onEditCallback(strEventName,sender)
		local edit = sender
		if strEventName == "changed" then
			local text = edit:getText()
			local ulen = string.counting(text)
			if ulen > NoticeMaxWordNum then
				local newStr = string.usubstr(text,NoticeMaxWordNum)
				if text~=newStr then
					edit:setText(newStr)
					text = newStr
					--display.pushToast(string.format(L("lua_code_text_315"), NoticeMaxWordNum))
				end
			end
		elseif strEventName == "ended" then
			local function checkCB( strTemp )
				if self and self._ui then
					local text = edit:getText()
					local ulen = string.counting(strTemp)
					edit:setText( strTemp )
					if ulen > NoticeMaxWordNum then
						display.pushToast(string.format(L("lua_code_text_315"), NoticeMaxWordNum))
					else
						executeFunc(self._onOperate, "change_guild_notice", strTemp )
					end
				end
			end

			local str = edit:getText()
			if app:isNeedCheckInput() then
				app:checkInput(str, function(response,errorMsg,code)
					if code == 200 then
						if response and response.result then
							str = response.result
							checkCB( str )
						end
					else
						display.pushToast(L("network_error"))
					end
				end, true)
			else
				checkCB( str )
			end
		end
	end
	local noticeEditBox = self._ui.Panel_left:findChild( "TextField" ) -- 公告编辑框
	self._editText = display.replaceTextFieldWithEditBox( noticeEditBox )
	self._editText:registerScriptEditBoxHandler(onEditCallback)
end

-- 宣言编辑框 处理
function ClassRef:_initDeclareEditBox()
	local function onEditCallback(strEventName,sender)
		local edit = sender
		if strEventName == "changed" then
			local text = edit:getText()
			local ulen = string.counting(text)
			if ulen > DeclareMaxWordNum then
				local newStr = string.usubstr(text,DeclareMaxWordNum)
				if text~=newStr then
					edit:setText(newStr)
					text = newStr
					--display.pushToast(string.format(L("lua_code_text_315"), DeclareMaxWordNum))
				end
			end
		end
	end
	local declareEditBox = self._ui.Panel_recruit:findChild( "TextField" ) -- 宣言编辑框
	self._declareText = display.replaceTextFieldWithEditBox( declareEditBox, cc.EDITBOX_INPUT_MODE_ANY )
	self._declareText:setPlaceholderFontColor( cc.c3b( 47, 12, 4 ) )
	self._declareText:registerScriptEditBoxHandler( onEditCallback )
end

function ClassRef:_selectedPanel( idx )
	if self._curIdx == idx then
		return
	end
	self._curIdx = idx

	for i = 1,3 do
		self._ui.Panel_btn:findChild(string.format( "Button_%d", i)):setBright( not( i == idx ) )
		self._ui.Panel_btn:findChild(string.format( "name_%d", i)):setOpacity( i == idx and 255 or 255 * 0.45 )
	end

	self._ui.Panel_recruit:setVisible(1 == idx)
	self._ui.Panel_list:setVisible(2 == idx)
	self._ui.Panel_set:setVisible(3 == idx)
	self:noApplicantTipsShown(false)
	executeFunc(self._onOperate, "guildManager_selectedPanel", idx )
end

-- 管理申请切页红点标记
function ClassRef:refreshNewApplyTips( applyTips )
	self._ui.Panel_btn:findChild( "dot_2" ):setVisible( applyTips )
end

-- 无申请者提示可见
function ClassRef:noApplicantTipsShown( shown )
	self._ui.no_tips:setVisible( shown )
end

-- 刷新左侧基础信息
function ClassRef:refreshGuildInfo( myGuildInfo )
	self._guildName:setString( myGuildInfo:getGuildName() ) -- 公会名字
	self._guildIcon:setData( myGuildInfo:getGuildIcon() ) -- 公会头像

	local memberStr = table.concat( { myGuildInfo:getGuildMemberNum(), "/", myGuildInfo:getGuildMaxMemberNum() } )
	self._onlineMemberNum:setString( memberStr ) -- 在线人数
	self._guildLv:setString( myGuildInfo:getGuildLv() ) -- 等级

	local lvUpNeedExp = tonumber( GD:queryGuildLvById( myGuildInfo:getGuildLv() ).exp or 0 ) -- 升级所需经验值
	if lvUpNeedExp > 0 then -- 存在下一级？
		self._guildExp:setPercentage( math.ceil( myGuildInfo:getGuildExp() / lvUpNeedExp * 100 ) )
	else
		self._guildExp:setPercentage( 100 ) -- 经验值进度条
	end

	self._guildCoinNum:setString( myGuildInfo:getGuildFund() ) -- 公会资金

	local guildNotice = myGuildInfo:getGuildNoticeContent()
	if "" ~= guildNotice then
		self._editText:setText( guildNotice ) -- 公告文本
	end

	local guildDeclare = myGuildInfo:getGuildDesc()
	if "" ~= guildDeclare then
		self._declareText:setText( guildDeclare ) -- 宣言文本
	end

	self:refreshGuildApplyPassSet(myGuildInfo)
	self._guildAutoPass = not myGuildInfo:needAuditing()
	self:setAutoApplyPassBtn(self._guildAutoPass)
	self:refreshMsdkGroupBinded()
end

--刷新公会审批设置
function ClassRef:refreshGuildApplyPassSet(myGuildInfo)
	self._needLv = myGuildInfo:autoApplyLvLimit()
	self._needPower = myGuildInfo:autoApplyCombatPowerLimit()
	self._needLvText:setString(self._needLv)
	self._needPowerText:setString(self._needPower)
end

function ClassRef:setAutoApplyLvLimit(lv)
	self._needLv = lv
	if self._needLv <= minPlayerLv then self._needLv = minPlayerLv end
	if self._needLv > maxPlayerLv then self._needLv = maxPlayerLv end
	--executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
	self._needLvText:setString(self._needLv)
	self:setAutoApplyPassBtn(false)
end

function ClassRef:_lvMinusBtnClickEvent(sender,eventType)
	self:_doLongPressClickEvent(sender,eventType,
		function()
			self:setAutoApplyLvLimit(self._needLv - 1)
		end)
end

function ClassRef:_lvPlusBtnClickEvent(sender,eventType)
	self:_doLongPressClickEvent(sender,eventType,
		function()
			self:setAutoApplyLvLimit(self._needLv + 1)
		end)
end

function ClassRef:setAutoApplyPowerLimit(power)
	self._needPower = power
	if self._needPower <= minCombatPower then self._needPower = minCombatPower end
	if self._needPower > maxCombatPower then self._needPower = maxCombatPower end
	--executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
	self._needPowerText:setString(self._needPower)
	self:setAutoApplyPassBtn(false)
end

function ClassRef:_powerMinusBtnClickEvent(sender,eventType)
	self:_doLongPressClickEvent(sender,eventType,
		function()
			self:setAutoApplyPowerLimit(self._needPower - 500)
		end)
end

function ClassRef:_powerPlusBtnClickEvent(sender,eventType)
	self:_doLongPressClickEvent(sender,eventType,
		function()
			self:setAutoApplyPowerLimit(self._needPower + 500)
		end)
end

function ClassRef:onOperate( cb )
	self._onOperate = cb
end

function ClassRef:_doLongPressClickEvent(sender,eventType,callFunc)
	if eventType == ccui.TouchEventType.began then
		self._delayPressAction = self:performWithDelay(
			function()
				if not self._longPressAction then
					self._longPressAction = self:schedule(callFunc,0.05)
				end
			end,0.3) --0.3秒后执行回调

	elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then

		if self._delayPressAction then
			self:stopAction(self._delayPressAction)
			self._delayPressAction = nil
		end

		if self._longPressAction then
			self:stopAction(self._longPressAction)
			self._longPressAction = nil
		else
			callFunc()
		end

		executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
	end
end

function ClassRef:setAutoApplyPassBtn(isAuto)
	self._autoApplyPassBtn:setBright(not isAuto)
	self._guildAutoPass = isAuto
	--if self._guildAutoPass ~= isAuto then

		--executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
	--end
end

function ClassRef:setAutoApplyPass(sender, eventType)
	if eventType == ccui.TouchEventType.ended then
		local curBright = self._autoApplyPassBtn:isBright()
		self:setAutoApplyPassBtn(curBright)
		executeFunc(self._onOperate, "changeApplyMode",{ternary(self._guildAutoPass,1,0),self._needLv,self._needPower})
	end
end

function ClassRef:refreshApplyListData(applyListData)
	self._applyList:reloadData(applyListData)

	if applyListData and #applyListData > 0 then
		self._ui.Panel_list:findChild("line1"):setVisible(true)
		self._ui.Panel_list:findChild("Button_quxiao"):setVisible(true)
		self._ui.Panel_list:findChild("Button_queding"):setVisible(true)
	else
		self._ui.Panel_list:findChild("line1"):setVisible(false)
		self._ui.Panel_list:findChild("Button_quxiao"):setVisible(false)
		self._ui.Panel_list:findChild("Button_queding"):setVisible(false)
	end
end


function ClassRef:_onMsdkGroupBind()
    if not app:isTencent() then
        return
	end

	local nowTime = app.session:getServerTime()
	if self._clickGroupTime then
		if nowTime - self._clickGroupTime <= 2 then
			return
		end
	end
	self._clickGroupTime = nowTime

    local isBind = UD.msdkData:getGroupBindedState()
	if isBind then
		local unbindDialog = display.newConfirmDialog(L("UnBindGroupConfirm"), function()
			UD.msdkData:unbindGroup()
		end)
		UIHandler:addPopDialog(unbindDialog)
    else
        UD.msdkData:createGroup()
	end
end

function ClassRef:refreshMsdkGroupBinded()
    if not app:isTencent() then
        return
	end
	local newguildModel = app:getInst("NewguildModel")
	if newguildModel then
		local leader = newguildModel:getGuildLeader()
		if leader and leader:getMemberId() == UD.player.uid then
			local isBind = UD.msdkData:getGroupBindedState()
			local wgPlatform = app.channelAPI:getWGPlatform()
			local width = self._ui["Panel/Panel_left"]:getContentSize2()
			if Enums.MSDK_PLATFORM.QQ == wgPlatform  then
				self._ui["Panel/Panel_left/Button_im"]:setVisible(true)
				self._ui["Panel/Panel_left/Button_im"]:setPositionX(0.7 * width)
				self._ui["Panel/Panel_left/Button_donate"]:setPositionX(0.3 * width)
		
				if  not isBind then
					self._ui["Panel/Panel_left/Button_im/name"]:setString(L("MSDK_BIND_GROUP"))
				else
					self._ui["Panel/Panel_left/Button_im/name"]:setString(L("MSDK_UNBINDED_GROUP"))
				end
			elseif Enums.MSDK_PLATFORM.WX == wgPlatform then
				self._ui["Panel/Panel_left/Button_im"]:setVisible(true)
				self._ui["Panel/Panel_left/Button_im"]:setPositionX(0.7 * width)
				self._ui["Panel/Panel_left/Button_donate"]:setPositionX(0.3 * width)
				if  not isBind then
					self._ui["Panel/Panel_left/Button_im/name"]:setString(L("MSDK_BIND_GROUP"))
				else
					self._ui["Panel/Panel_left/Button_im/name"]:setString(L("MSDK_UNBINDED_GROUP"))
				end
			end
		end
	end
end

return ClassRef
